package com.fare.taluo.web.action;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import com.common.remote.ftp.FtpConfig;
import com.common.remote.sftp.SFtpFileTransferClient;
import com.dayatang.domain.InstanceFactory;
import com.fare.taluo.application.CaptureDataExportApplication;
import com.fare.taluo.application.ExcelInfoApplication;
import com.fare.taluo.application.plane.channel.SourceApplication;
import com.fare.taluo.conf.system.DefaultPropertiesLoader;
import com.fare.taluo.vo.core.ExcelInfoVO;
import com.fare.taluo.vo.core.SourceEntityVO;
import com.fare.util.ReportProperties;

public class ExcelAutoCreate {
	
//	@Resource(name="departmentServiceImpl")
//	private DepartmentService departmentServiceImpl;
	
//	@Resource(name="captureDataExportApplicationImpl")
//	private CaptureDataExportApplication captureDataExportApplication;
//	
//	@Inject
//	private ExcelInfoApplication excelInfoApplication;
	
//	private Logger log = Logger.getLogger(ExcelAutoCreate.class);
	
	

	public void execute() throws Exception{
		SourceApplication sourceApplication =InstanceFactory.getInstance(SourceApplication.class);
		CaptureDataExportApplication captureDataExportApplication=InstanceFactory.getInstance(CaptureDataExportApplication.class);
		ExcelInfoApplication excelInfoApplication=InstanceFactory.getInstance(ExcelInfoApplication.class);
	//	log.info("处理任务开始>........");
		Date date =new Date();
		Calendar calendar=Calendar.getInstance();   
		calendar.setTime(date);
		calendar.add(Calendar.HOUR_OF_DAY, -1);
		date =calendar.getTime();
		SimpleDateFormat sdfType= new SimpleDateFormat("yyyy-MM-dd HH");
		SimpleDateFormat sdfType1= new SimpleDateFormat("yyyyMMddHH");
		String dateType =sdfType.format(date);
		String dateType1=sdfType1.format(date);
		String year =dateType1.substring(0, 4);
		String month =dateType1.substring(4, 6);
		String day =dateType1.substring(6,8);
		String hour =dateType1.substring(8, 10);
		List<SourceEntityVO>  list= sourceApplication.findAllSourceEntity();
		//取得配置文件实例
		ReportProperties rp=ReportProperties.getInstance();
		//ftp连接配置
		FtpConfig config=new FtpConfig(rp.getAddress(),rp.getPort(),rp.getUserName(),rp.getPassword());
		SFtpFileTransferClient sftpClient=new SFtpFileTransferClient(config);
		String dir=rp.getPath()+"excel"+"/"+year+"-"+month+"/"+day+"/"+hour;//文件目录路径
		InputStream in =null;
		File allFile = new File(DefaultPropertiesLoader.getAppExcelFilePath()+dateType+".zip");
		FileOutputStream fousAll = new FileOutputStream(allFile); 
		ZipOutputStream zipOutAll = new ZipOutputStream(fousAll);
		boolean filebind =false;
		try {
			for(SourceEntityVO sourceVo : list){
				String code=sourceVo.getHbaseKey();
				String fileName =sourceVo.getName()+'('+dateType+')';
				List<ExcelInfoVO> listvo =excelInfoApplication.findBycodeAndTime(code, dateType1);
				if(listvo!=null && listvo.size()>0){
					continue;
				}
				String result = captureDataExportApplication.exportExcelByTime(date, code,fileName);
				
			//	System.out.print(result);
				if("nodata".equals(result)){
				//	status = "nodata";
				}else{
					
				    /**创建一个临时压缩文件，
		             * 我们会把文件流全部注入到这个文件中
		             * 这里的文件你可以自定义是.rar还是.zip*/
		            File file = new File(DefaultPropertiesLoader.getAppExcelFilePath()+code+'('+dateType+')'+".zip");
		            FileOutputStream fous = new FileOutputStream(file);  
		            /**打包的方法我们会用到ZipOutputStream这样一个输出流,
		             * 所以这里我们把输出流转换一下*/
		           ZipOutputStream zipOut
		            = new ZipOutputStream(fous);
		            /**这个方法接受的就是一个所要打包文件的集合，
		             * 还有一个ZipOutputStream*/
		           	zipFile(new File(result), zipOut);
		           	zipFile(new File(result),zipOutAll);
		           	filebind =true;
		            zipOut.close();
		            fous.close();
					boolean flag=false;
					flag = sftpClient.connect();
					
					
					//一级一级创建目录
					String[] dirs=dir.split("/");
					StringBuffer buffer=new StringBuffer();
					for(String d:dirs){
						buffer.append(d+"/");
						//System.out.println(buffer.toString());
						if(!sftpClient.isDirectoryExists(buffer.toString())){
							sftpClient.makeDirectory(buffer.toString());
						}
					}
					in=new FileInputStream(file);
					sftpClient.upload(in, dir+"/"+fileName+".zip");
					ExcelInfoVO excelInfoVO =new ExcelInfoVO();
					excelInfoVO.setCode(code);
					excelInfoVO.setDateType(dateType1);
					excelInfoVO.setName(fileName);
					excelInfoVO.setPath("excel"+"/"+year+"-"+month+"/"+day+"/"+hour+"/"+fileName+".zip");
					excelInfoVO.setUploadDate(new Date());
					excelInfoApplication.saveOrUpdate(excelInfoVO);
					in.close();
					file.delete();
					File f =new File(result);
					f.delete();
				}
			}	
			if(filebind){
				zipOutAll.close();
				in=new FileInputStream(allFile);
				sftpClient.upload(in, dir+"/"+dateType+".zip");
				in.close();
			}
			allFile.delete();
			
				
				
			
			} catch (Exception e) {
		//		log.error("处理任务出现异常", e);
				System.out.print("Excel表生成出现异常");
				e.printStackTrace();
			} finally{
				sftpClient.disconnect();
				try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e) {
			}
		}

	}

	/**
	 * 根据输入的文件与输出流对文件进行打包
	 * 
	 * @param File
	 * @param org
	 *            .apache.tools.zip.ZipOutputStream
	 */
	private void zipFile(File inputFile, ZipOutputStream ouputStream) {
		try {
			if (inputFile.exists()) {
				/**
				 * 如果是目录的话这里是不采取操作的， 至于目录的打包正在研究中
				 */
				if (inputFile.isFile()) {
					FileInputStream IN = new FileInputStream(inputFile);
					BufferedInputStream bins = new BufferedInputStream(IN, 512);
					// org.apache.tools.zip.ZipEntry
					ZipEntry entry = new ZipEntry(inputFile.getName());
					ouputStream.putNextEntry(entry);
					// 向压缩文件中输出数据
					int nNumber;
					byte[] buffer = new byte[512];
					while ((nNumber = bins.read(buffer)) != -1) {
						ouputStream.write(buffer, 0, nNumber);
					}
					// 关闭创建的流对象
					bins.close();
					IN.close();
				} else {
					try {
						File[] files = inputFile.listFiles();
						for (int i = 0; i < files.length; i++) {
							zipFile(files[i], ouputStream);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
    } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
